<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: {2021/1/11}
 * Time: {16:08}
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\common\lib\sms;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\Exception;
use think\facade\Log;

class AliSms implements BaseSms
{
    /**
     * @param string $phone_number
     * @param int $code
     * @return array|mixed
     * @throws Exception
     */
    public static function sendSms(string $phone_number = '', int $code = 0)
    {
        $data = [
            "code" => $code
        ];
        //dump($data);exit();
        $config = config('aliyun');
        try {
            AlibabaCloud::accessKeyClient($config['accessKeyId'], $config['accessSecret'])
                ->regionId($config['regionId'])
                ->asDefaultClient();
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host($config['host'])
                ->options([
                    'query' => [
                        'RegionId' => $config['regionId'],
                        'PhoneNumbers' => $phone_number,
                        'SignName' => $config['SignName'],
                        'TemplateCode' => $config['TemplateCode'],
                        'TemplateParam' => json_encode($data),
                    ],
                ])
                ->request();
        } catch (\Exception $e) {
            Log::error("{$phone_number} sendSms" . $e->getMessage());
            throw new Exception("系统内部异常!发送验证码失败");
        }
        $ret = $result->toArray();
        if ($ret['Code'] === "OK") {
            return true;
        } else {
            Log::error("{$phone_number} 发送验证码失败:" . json_encode($ret));
            return false;
        }
    }
}